/**
 * Created by DELL on 2018-03-08.
 */
var baseUrl={
    // 使用base，pro弃用
    //pro:'http://47.92.39.186/xrtn-manager/',
    base:'http://localhost:8080/xrtn-manager/',
    // base:'http://devadmin.xrtn.dmpp.net.cn/xrtn-manager/',
    // base:'http://admin.xrtn.dmpp.net.cn/xrtn-manager/',
    patient:'patient/',
    user : 'user/',
    card : 'card/',
    sysuser : 'sysuser/',
    order : 'order/',
    booking : 'booking/',
    subclinic : 'subclinic/',
    service : 'service/',
    role : 'role/',
    init:'init/',
    auth : 'auth/',
    ad:'ad/',
    special:'special/',
    tempHeadImg:'http://image.xrtn.dmpp.net.cn/common/userDefaultIcon.png',
    gobase:'',
    patientImg:'http://image.xrtn.dmpp.net.cn/common/patientDefaultIcon.png',
    sysUserImg:'http://image.xrtn.dmpp.net.cn/common/sysUserDefaultIcon.jpg',
    goUrl:function(url){
        return this.base+url
    }
}
var pathUrl={
    gotoStoreSetting:(baseUrl.goUrl('subclinic/gotoStoreSetting')),
    gotoStoreDetail:(baseUrl.goUrl('subclinic/gotoStoreDetail')),
}
var initValue = {
    subclinicId : 1
}

var SessionData={}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
// let time1 = new Date().Format("yyyy-MM-dd");
// let time2 = new Date().Format("yyyy-MM-dd HH:mm:ss");

Date.prototype.Format = function (fmt) { //author: meizz
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

var baseFn = {
    goPath:function(urlName,obj,type){
        if(urlName == '-1'){
            window.history.go(urlName)
            return;
        }
        var _pathData={
            base:baseUrl.base,
            gotoStoreDetail: 'subclinic/gotoStoreDetail',
            gotoFastOrder:'order/gotoFastOrder',//绿色通道页面
            gotoHomeGoods:'order/gotoHomeGoods',//购买商品页面
            gotoCtaffManagement_q:'sysuser/gotoCtaffManagement_q',//离职员工页面
            gotoOrder:'order/gotoOrder',//订单列表
            gotoOrderDetail:'order/gotoOrderDetail',//订单详情
            gotoAddCard:'card/gotoAddCard',//卡项详情
            gotoCardManagement:'card/gotoCardManagement',//卡项管理页面
            couponContent:'card/couponContent',//卡项详情
            gotoCouponManagement:'card/gotoCouponManagement',//优惠券管理页面
            gotoStoreSetting:'subclinic/gotoStoreSetting',//门店管理
            gotoAddVip:'user/gotoAddVip',//会员中心 新增编辑
            gotoVip:'user/gotoVip',//会员中心 列表
            gotoVipDetail:'user/gotoVipDetail',//会员中心 详情
            gotoHomeRecharge:'user/gotoHomeRecharge',//会员中心 充值
            gotoUserlib:'patient/gotoUserlib',//病人库 宝宝中心
            gotoPatientInfo:'patient/gotoPatientInfo',//病人详情
            gotoTreatStat:'patient/gotoTreatStat',//病人库 病历管理
            gotoCtaffManagement:'sysuser/gotoCtaffManagement',//员工管理列表
            gotoCtaffManagementInfo:'sysuser/gotoCtaffManagementInfo',//员工详情
            gotoSysUserReplyInfo:'sysuser/gotoSysUserReplyInfo',//员工评价详情
            gotoBespeak:'booking/gotoBespeak',//预约管理
            gotoBespeakInfoDetail:'booking/gotoBespeakInfoDetail',//预约信息详情
            gotoAddSysUser:'sysuser/gotoAddSysUser',//新增员工
            gotoBooking:'booking/gotoBooking',//新增预约（新）
            gotoSysUserAchievements:'sysuser/gotoSysUserAchievements',//员工绩效列表
            gotoCtaffManagementDetail:'sysuser/gotoCtaffManagementDetail',//员工绩效明细
            exportBookingList:'excel/exportBookingList',//导出预约数据
            exportPatientList:'excel/exportPatientList',//导出宝宝
            exportTreatmentList:'excel/exportTreatmentList',//导出病历
            gotoGoodsSetting:'init/gotoGoodsSetting',//商品单列表
        } 
        if(type){
            if(type == 'url'){
                return _pathData.base + _pathData[urlName]
            }
        }
        var _gourl = _pathData.base + _pathData[urlName]
        if(this.notNull(obj)){
            _gourl += '?'
            for(var i in (obj || {})){
                _gourl += i+'='+obj[i]+'&'
            }
            if(type && type == 'urlData'){
                return _gourl.substring(0,_gourl.length-1)
            }
            window.location.href= _gourl.substring(0,_gourl.length-1)
        }else{
            window.location.href= _gourl
        }
    },
    getSession:function(data){
        var that=this;
        SessionData={
            menu:[],
            power:[],
            userId:$('input[name=xrtnUserId]').val(),
            userName:$('input[name=xrtnUserName]').val(),
            userNo:$('input[name=xrtnUserNo]').val(),
            userImg:$('input[name=xrtnUserImg]').val(),
            subclinicName:$('input[name=xrtnSubclinicName]').val(),
            subclinicId:$('input[name=xrtnSubclinicId]').val(),
        }
        if(data){
            for(var i=0;i<data.length;i++){
                SessionData.menu.push(data[i].menuId)
                var _fu = data[i].functionList
                if(that.notNull(_fu)){
                    for(var j=0;j<_fu.length;j++){
                        SessionData.power.push(_fu[j].functionId)
                    }
                }
                
            }
        }
        // SessionData.power=[0, 1, 2, 3, 4, 5, 6, 7,8,9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,44,45,  46,47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
        baseUrl.gobase=$('input[name=xrtngoUrl]').val()+'/'
        $('div.js_session_data').remove()
        SessionData.powerSub=(that.getPower(45)?SessionData.subclinicId:false)
    },
    getPower:function(opts,type){
        var that=this,_bo=true,_power=SessionData.power;
        if(type){
            _power = SessionData.menu 
        }
        if(that.isArray(opts)){
            
        }else{
            opts=[opts]
        }
        for(var i=0;i<opts.length;i++){
            var _temp=opts[i]
            _bo = SessionData.power.every(function(val){
                return val != _temp
            })
            if(!_bo){
                return _bo
            }
        }
        return _bo
    },
    powerFn:function(){
        var that = this
        //权限控制
        if(that.getPower(1)){//工作台 查看商品消耗详情
            $('.js_power_1').addClass('hidden').remove()
        }
        if(that.getPower(2)){//工作台 绿色通道
            $('.js_power_2').addClass('hidden')
        }
        if(that.getPower(3)){//工作台 新增预约
            $('.js_power_3').addClass('hidden')
        }
        if(that.getPower(4)){//工作台 快速开卡
            $('.js_power_4').addClass('hidden')
        }
        if(that.getPower(5)){//工作台 会员储
            $('.js_power_5').addClass('hidden')
        }
        if(that.getPower(6)){//工作台 新增会员
            $('.js_power_6').addClass('hidden')
        }
        if(that.getPower(63)){//工作台 预约管理
            $('.js_power_63').addClass('hidden')
        }
        if(that.getPower(64)){//工作台 今日预约
            $('.js_power_64').addClass('hidden')
            $('.js_power_64').attr('href','javascript:void(0)')
            $('.js_power_64').on('click',function(){
                that.infoDialog('您没有权限进行该操作！')
            })
        }
        if(that.getPower(65)){//工作台 代收款
            $('.js_power_65').addClass('hidden')
            $('.js_power_65').attr('href','javascript:void(0)')
            $('.js_power_65').on('click',function(){
                that.infoDialog('您没有权限进行该操作！')
            })
        }
        if(that.getPower(71)){//工作台 购买商品
            $('.js_power_71').addClass('hidden')
        }
        if(that.getPower(8)){//预约管理 预约列表
            $('.js_power_8').addClass('hidden')
        }
        if(that.getPower(9)){//预约管理 预约看板
            $('.js_power_9').addClass('hidden')
        }
        if(that.getPower(47)){//预约管理 预约信息
            $('.js_power_47').addClass('hidden')
        }
        //预约管理都不存在的情况
        if(that.getPower(8) && that.getPower(9) && that.getPower(47)){
            $('.js_power_8_9_47').addClass('hidden')
        }
        if(that.getPower(10)){//预约管理 新增预约
            $('.js_power_10').addClass('hidden')
        }
        if(that.getPower(67)){//病人库 导出宝宝信息
            $('.js_power_67').addClass('hidden')
        }else{
            $('.js_power_67').attr('href',$('.js_power_67').attr('href')+'subclinicId='+SessionData.subclinicId)
        }
        if(that.getPower(12)){//订单管理 绿色通道
            $('.js_power_12').addClass('hidden')
        }
        if(that.getPower(52)){//订单管理 快速开卡
            $('.js_power_52').addClass('hidden')
        }
        if(that.getPower(53)){//订单管理 会员储值
            $('.js_power_53').addClass('hidden')
        }
        if(that.getPower(49)){//订单管理 就诊订单tab
            $('.js_power_49').addClass('hidden')
        }
        if(that.getPower(50)){//订单管理 卡项订单tab
            $('.js_power_50').addClass('hidden')
        }
        
        //订单管理的tab都不存在的情况
        if(that.getPower(49) && that.getPower(50) && that.getPower(69)){
            $('.js_power_49_50_69').addClass('hidden')
        }
        if(that.getPower(70)){//订单管理 购买商品
            $('.js_power_70').addClass('hidden')
        }
        if(that.getPower(80)){//订单详情 修改推拿师
            $('.js_power_80').addClass('hidden')
        }
        if(that.getPower(82)){//订单详情 修改支付方式
            $('.js_power_82').addClass('hidden')
        }
        if(that.getPower(54)){//病人库 宝宝中心tab
            $('.js_power_54').addClass('hidden')
            $('.js_power_54_55').find('a').attr('href',baseFn.goPath('gotoTreatStat',{},'url'))
        }
        if(that.getPower(81)){//病人库 宝宝中心tab
            $('.js_power_81').addClass('hidden')
        }
        if(that.getPower(55)){//病人库 病历管理tab
            $('.js_power_55').addClass('hidden')
        }
        //病人库的tab都不存在的情况
        if(that.getPower(54) && that.getPower(55)){
            $('.js_power_54_55').addClass('hidden')
        }
        if(that.getPower(14)){//病人库 导出宝宝病历信息
            $('.js_power_14').addClass('hidden')
        }else{
            $('.js_power_14').attr('href',$('.js_power_14').attr('href')+'subclinicId='+SessionData.subclinicId)
        }
        if(that.getPower(66)){//病人库 导出宝宝信息
            $('.js_power_66').addClass('hidden')
        }else{
            $('.js_power_66').attr('href',$('.js_power_66').attr('href')+'subclinicId='+SessionData.subclinicId)
        }
        if(that.getPower(16)){//病人库 编辑宝宝信息
            $('.js_power_16').addClass('hidden')
        }
        if(that.getPower(17)){//病人库 查看家庭护理详情
            $('.js_power_17').addClass('hidden')
        }
        if(that.getPower(19)){//会员中心 添加会员
            $('.js_power_19').addClass('hidden')
        }
        if(that.getPower(75)){//会员中心 会员充值
            $('.js_power_75').addClass('hidden')
        }
        if(that.getPower(79)){//会员中心 会员对账
            $('.js_power_79').addClass('hidden')
        }
        if(that.getPower(87)){//会员中心 导出会员
            $('.js_power_87').addClass('hidden')
        }
        //权限管理 会员中心 - 编辑详情
        if(baseFn.getPower(68)){
            $('.js_power_68').remove()
        }
        if(that.getPower(21)){//会员中心 申请退款
            $('.js_power_21').addClass('hidden')
        }
        if(that.getPower(24) && that.getPower(25)){//卡券管理 卡项管理&优惠券管理
            $('.js_power_24_25').addClass('hidden')
        }
        if(that.getPower(24)){//卡券管理 卡项管理
            $('.js_power_24').addClass('hidden').remove()
        }
        if(that.getPower(25)){//卡券管理 优惠券管理
            $('.js_power_25').addClass('hidden').remove()
        }
        if(that.getPower(26)){//卡券管理 添加/编辑/下架/删除卡项
            $('.js_power_26').addClass('hidden').remove()
            $('.Baby_Healthy_home_right_bespeak_search.js_cardpage').css({'height':0})
        }
        if(that.getPower(27)){//卡券管理 添加/下架/编辑/删除优惠券
            $('.js_power_27').addClass('hidden').remove()
            $('.Baby_Healthy_home_right_bespeak_search.js_couponpage').css({'height':0})
        }
        if(that.getPower(31)){//门店管理 项目设置（服务设置）
            $('.js_power_31').addClass('hidden').remove()
        }
        if(that.getPower(32)){//门店管理 商品设置
            $('.js_power_32').addClass('hidden').remove()
        }
        if(that.getPower(57)){//门店管理 添加服务
            $('.js_power_57').addClass('hidden').remove()
            $('.js_power_57_wrap').css('height',0)
        }
        if(that.getPower(60)){//门店管理 添加商品
            $('.js_power_60').addClass('hidden').remove()
        }
        if(that.getPower(33)){//门店管理 查看商品消耗统计
            $('.js_power_33').addClass('hidden').remove()
        }
        if(that.getPower(34)){//员工管理 添加员工
            $('.js_power_34').addClass('hidden').remove()
        }
        if(that.getPower(35)){//员工管理 查看已离职员工
            $('.js_power_35').addClass('hidden').remove()
        }
        if(that.getPower(36)){//员工管理 查看员工绩效
            $('.js_power_36').addClass('hidden').remove()
        }
        if(that.getPower(37)){//员工管理 辞退员工
            $('.js_power_37').addClass('disabled')
        }
        if(that.getPower(39)){//员工管理 员工离职
            $('.js_power_39').addClass('disabled')
        }
        if(that.getPower(40)){//基础设置 首页广播/轮播设置
            $('.js_power_40').addClass('hidden').remove()
        }
        if(that.getPower(41)){//基础设置 分店广播/轮播设置
            $('.js_power_41').addClass('hidden').remove()
        }
        if(that.getPower(40) && that.getPower(41)){//基础设置 基础设置
            $('.js_power_40_41').addClass('hidden').remove()
        }
        if(that.getPower(44)){//基础设置 角色设置
            $('.js_power_44').addClass('hidden').remove()
        }
        if(that.getPower(40) && that.getPower(41) && that.getPower(44)){//基础设置 基础设置目录
            $('.js_power_40_41_44').addClass('hidden')
        }
        if(that.getPower(45)){//基础设置 查看全部门店
            $('.js_power_45').prop('disabled',true)
        }
    },
    getHidePhoneStr:function(userPhone) {
        return !baseFn.getPower(85) ? userPhone : userPhone.substring(0,3) + "****" + userPhone.substring(userPhone.length - 4, userPhone.length);
    },
    timestampToTime:function(timestamp,ntxt) {
        if(this.notNull(timestamp)){
            var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
            Y = date.getFullYear() + '-';
            M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
            D = (date.getDate()<10?'0'+date.getDate():date.getDate()) + ' ';
            h = (date.getHours()<10? '0'+(date.getHours()) : date.getHours()) + ':';
            m = (date.getMinutes()<10? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
            s = date.getSeconds()<10? '0'+(date.getSeconds()) : date.getSeconds();
            return Y+M+D+h+m+s;
        }else{
            if(ntxt){
                return ntxt
            }else{
                return '无'
            }
        }
    },
    goDay:function(backday,type){
        if(typeof Number(backday) == 'number' && Number(backday) != NaN){
            var _todayParse=Date.parse(new Date()),_backdaysParse=(60*60*24*1000)*Number(backday);
            var _dayParse = _backdaysParse+_todayParse
            if(arguments[1]){
                if(arguments[1] = 1){
                    //年月日
                    _dayParse = this.timestampToTime(_dayParse).substring(0,10)
                }else if(arguments[1] = 2){
                    //年月日 时分
                    _dayParse = this.timestampToTime(_dayParse).substring(0,16)
                }else if(arguments[1] = 3){
                    //年月日 时分秒
                    _dayParse = this.timestampToTime(_dayParse)
                }
            }
            return _dayParse
            
        }else{
            this.infoDialog('输入的不是数字！')
        }
        
        
    },
    formatDate:function(elm){
        if(String(elm).length == 1){
            return '0'+ String(elm)
        }
        return elm
    },
    getDateWeek:function(dateStr){ // 返回周几
        var weekDay = ["周天", "周一", "周二", "周三", "周四", "周五", "周六"];
        var myDate = new Date(Date.parse(dateStr.replace(/-/g, "/")));
        return weekDay[myDate.getDay()]
    },
    uniqueArr:function(arr){
        var res = [];
        var json = {};
        for(var i = 0; i < arr.length; i++){
            if(!json[arr[i]]){
            res.push(arr[i]);
            json[arr[i]] = 1;
            }
        }
        return res;
    },
    dialog:function(options){
        //dialog's opts
        //dialog
        var defaults={
            title: '温馨提示',
            content: '生命的起源归于自然',
            okValue: '确定',
            ok: function(){},
            cancelValue: "取消",
            cancel: '' ,
            width:'250'
        }
        var settings = $.extend({}, defaults, options);
        var d = dialog(settings).showModal();
        $('.ui-dialog-title').css({
            'width': '100%',
            'text-align': 'center',
            /* font-weight: normal; */
            'font-size': '15px',
            'box-sizing': 'border-box',
            'padding': '14px 15px'
        })
        $('.ui-dialog-close').css({
            'position': 'absolute',
            'font-weight': 'normal',
            'top': '14px',
            'opacity':' 0.7',
            'font-size': '24px',
            'right': '10px'
        })
        $('.ui-dialog-body').css({
            'padding':'30px'
        })
        // $('.ui-dialog-button').css({
        //     'margin':'0.8rem 1.3rem 0.8rem auto'
        // })
        $('.ui-dialog-button').css({
            'margin':'0.8rem 2rem 0.8rem auto'
        })
        $('.ui-dialog-footer').css({
            'padding': '5px 0 4px 20px',
            'background-color': '#f2f2f2'
        })
        $('.ui-dialog-button button').css({
            'border-radius': '2px',
            'padding': '4px 22px'
        })
        $('.ui-dialog-autofocus').css({
            'background': '#53C7FF'
        })
        return d
    },
    infoDialog:function(cnt,callback,times,hasbtn){
        //dialog's opts(提示内容，“确定ok”回调函数,显示时间间隔)
        //dialog
        var defaults={
            title: '提示',
            content: '对话框将在一秒内关闭',
            okValue: '确定',
            ok: hasbtn || false,
            cancelValue: "取消",
            cancel: '' ,
            width:'250'
        }
        var _times=2500,_callback=function(){}
        if(times != undefined && times != ''){
            _times = times
        }
        if(callback != undefined && callback != ''){
            _callback = callback
        }
        var settings = $.extend({}, defaults, {content:cnt,callback:_callback,times:_times});
        
        var d = dialog(settings).showModal();
        d.show();
        setTimeout(function () {
            d.close().remove();
            settings.callback()
        }, settings.times);
        $('.ui-dialog-title').css({
            'width': '100%',
            'text-align': 'center',
            /* font-weight: normal; */
            'font-size': '15px',
            'box-sizing': 'border-box',
            'padding': '14px 15px'
        })
        $('.ui-dialog-close').css({
            'position': 'absolute',
            'font-weight': 'normal',
            'top': '14px',
            'opacity':' 0.7',
            'font-size': '24px',
            'right': '10px'
        })
        $('.ui-dialog-body').css({
            'padding':'30px'
        })
        $('.ui-dialog-button').css({
            'margin':'0.8rem 1.3rem 0.8rem auto'
        })
        $('.ui-dialog-footer').css({
            'padding': '5px 0 4px 20px',
            'background-color': '#f2f2f2'
        })
        $('.ui-dialog-button button').css({
            'border-radius': '2px',
            'padding': '4px 22px'
        })
    },
    rpSelect:function(domName,_objs){
        var $sObj = $(domName)
        $sObj.args = $.extend({
            dataSrc:'results',
            idKey:"id",
            textKey:'text',
            isId:false,
            sel:'',
            url:'',
            type:'GET',
            baseData:{sel:1},
            data:{},
            datas:[],
            multiple:false,
            placeholder:'请选择选项',
            valide:'',
            hasAll:false,
            hasAllId:'none',
            hasAllText:'全部',
            calFn:function(dom,data){},
            selFn:function(e){}
        },_objs||{});
        $sObj.init = function(){
            var _data = $.extend({},$sObj.args.baseData,$sObj.args.data)
            if($sObj.args.datas.length != 0){
                setTimeout(function(){//延迟一下 vue数据更新时就不会出现无法使用的问题了
                    var _tempData = $sObj.args.datas,_datas=[]
                    for(var k2=0;k2<_tempData.length;k2++){
                        _datas.push({
                            id:_tempData[k2][$sObj.args.idKey],
                            text:_tempData[k2][$sObj.args.textKey]
                        })
                    }
                    if($sObj.args.hasAll){
                        _datas.splice(0,0,{id:$sObj.args.hasAllId,text:$sObj.args.hasAllText})
                    }

                    $sObj.select2({
                        placeholder:$sObj.args.placeholder,
                        data:_datas,
                        multiple: $sObj.args.multiple,
                        closeOnSelect: !$sObj.args.multiple
                    })
                    if($sObj.args.valide && $sObj.args.valide != ''){
                        $sObj.on("select2:close", function (e) {
                            var _check = $sObj.args.valide.check(false,$(e.currentTarget))
                        });
                        $sObj.on("select2:select", function (e) {
                            var _check = $sObj.args.valide.check(false,$(e.currentTarget))
                        });
                        $sObj.on("select2:unselect", function (e) {
                            $sObj.args.valide.check(false,$(e.currentTarget))
                        });
                    }else{
                        $sObj.on("select2:close", function (e) {
                            
                        });
                        $sObj.on("select2:select", function (e) {
                            $sObj.args.selFn(e)
                        });
                        $sObj.on("select2:unselect", function (e) {
                            
                        });
                    }
                    $sObj.args.calFn($(domName),$sObj.args.datas)
                },0)

            }else{
                $.ajax({
                    url:$sObj.args.url,
                    type:$sObj.args.type,
                    data:_data,
                    dataType:"json",
                    success:function(res){
                        if(res.code == 0){
                            var _srcs = $sObj.args.dataSrc.split('.'),_len=_srcs.length
                            var _tempData = res
                            for(var x in _srcs){
                                _tempData = _tempData[_srcs[x]]
                            }

                            if(_len == 2){
                                _tempData = res[_srcs[0]][_srcs[1]]
                            }
                            if(!(Object.prototype.toString.call(_tempData)=='[object Array]')){
                                //如果返回数据是个对象的话 转为单元素数组
                                if(_tempData == null || _tempData == undefined){
                                    _tempData = []
                                }else{
                                    _tempData = [_tempData]
                                } 
                            }
                            for(var k1=0;k1<_tempData.length;k1++){
                                $sObj.args.datas.push({
                                    id:_tempData[k1][$sObj.args.idKey],
                                    text:_tempData[k1][$sObj.args.textKey],
                                })
                            }
                            if($sObj.args.hasAll){
                                $sObj.args.datas.splice(0,0,{id:$sObj.args.hasAllId,text:$sObj.args.hasAllText})
                            }
                            
                        }
                        $sObj.select2({
                            placeholder:$sObj.args.placeholder,
                            data:$sObj.args.datas,
                            multiple: $sObj.args.multiple,
                            closeOnSelect: !$sObj.args.multiple
                        })
                        if($sObj.args.valide && $sObj.args.valide != ''){
                            $sObj.on("select2:close", function (e) {
                                var _check = $sObj.args.valide.check(false,$(e.currentTarget))
                            });
                            $sObj.on("select2:select", function (e) {
                                var _check = $sObj.args.valide.check(false,$(e.currentTarget))
                            });
                            $sObj.on("select2:unselect", function (e) {
                                $sObj.args.valide.check(false,$(e.currentTarget))
                            });
                        }else{
                            $sObj.on("select2:close", function (e) {
                                
                            });
                            $sObj.on("select2:select", function (e) {
                                $sObj.args.selFn(e)
                            });
                            $sObj.on("select2:unselect", function (e) {
                                
                            });
                        }
                        $sObj.args.calFn($(domName),$sObj.args.datas)

                    },
                    complete:function(res){
                        //$sObj.args.calFn($(domName),$sObj.args.datas)
                    },
                    error:function(res){
                        console.log(res)
                    }
                })
            }
            // if($sObj.args.multiple){
            //     $(($sObj.args.isId?'#':'.') + $sObj.args.sel).on("select2:select", function (e) {
            //         // $(($sObj.args.isId?'#':'.') + $sObj.args.sel).select2('open')
            //     });
            //     $(($sObj.args.isId?'#':'.') + $sObj.args.sel).on("select2:close", function (e) {

            //     });
            // }
        }
        $sObj.init()
    },
    rpDataTables:function(domName,_objs){
        var defaults={
            dom: 'rt<"bottom"ip<"clear">>',
            lang:'./js/cn_lang.json',
            ajUrl:'',
            ajDataSrc:'results',
            ajData:{},
            ajType:'get',
            select:false,
            columns:[],
            autoWidth:true,
            displayLength:10,
            scrollY:200,
            scrollCollapse: true,
            service:false,
            serviceTotal:'results.records',
            drawCallback:function(){},
            initComplete:function(){},
            init:function(){},//初始化之后的函数
            selecd:function(){},
            deselecd:function(){},
            page:function(){},
            curPage:1
        }
        var settings = $.extend({}, defaults, _objs);

        var _udata={
            userId:'1'
        }
        var _tbConfig={
            "dom": settings.dom,
            language:{
                "sProcessing": "处理中...",
                "sLengthMenu": "显示 _MENU_ 项结果",
                "sZeroRecords": "没有匹配结果",
                "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
                "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                "sInfoPostFix": "",
                "sSearch": "搜索:",
                "sUrl": "",
                "sEmptyTable": "没有数据",
                "sLoadingRecords": "载入中...",
                "sInfoThousands": ",",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "上页",
                    "sNext": "下页",
                    "sLast": "末页"
                },
                "oAria": {
                    "sSortAscending": ": 以升序排列此列",
                    "sSortDescending": ": 以降序排列此列"
                },
                "select": {
                    "rows": ""
                }
            },
            width:'100%',
            select:settings.select,
            page: settings.page,
            sessionPageKey: settings.sessionPageKey,
            ordering:false,
            columns:settings.columns,
            drawCallback:settings.drawCallback,
            autoWidth:settings.autoWidth,
            displayLength:settings.displayLength,
            scrollY:settings.scrollY,
            scrollCollapse:settings.scrollCollapse
        }
        var that = this
        _tbConfig.initComplete = function () {
            if (baseFn.notNull($.session.get(settings.sessionPageKey))){
                var page = $.session.get(settings.sessionPageKey);
                _dataTable.page(page - 1).draw(false);
            }
            settings.initComplete();
        }


        if(settings.ajUrl != '' && settings.ajUrl != null && settings.ajUrl != undefined && !settings.service){
            _tbConfig.ajax={
                url:settings.ajUrl,
                dataSrc: settings.ajDataSrc,
                data:settings.ajData,
                type:settings.ajType
            }
        }else if(typeof settings.datas == 'object' || typeof settings.datas == 'array' ){
            _tbConfig.data = settings.datas
        }else if(settings.ajUrl != '' && settings.ajUrl != null && settings.ajUrl != undefined && settings.service){
            _tbConfig.serverSide=true;
            // var _notFirst_ = false
            _tbConfig.ajax=function(data,callback,sets){

                if (baseFn.notNull($.session.get(settings.sessionPageKey))){
                    settings.ajData.page = $.session.get(settings.sessionPageKey);
                }else {
                    settings.ajData.page = (data.start / data.length)+1;//当前页码
                }

                $.ajax({
                    url:settings.ajUrl,
                    type:settings.ajType,
                    data:settings.ajData,
                    cache: false,
                    dataType:"json",
                    success:function(res){
                        if(res.code == 0){
                            var _srcs = settings.ajDataSrc.split('.'),_len=_srcs.length
                            var _tempData = that.objDeepCopy(res)
                            for(var x in _srcs){
                                _tempData = _tempData[_srcs[x]]
                            }
                            var _totalsrc = settings.serviceTotal.split('.')
                            var _total = that.objDeepCopy(res)
                            for(var y in _totalsrc){
                                _total = _total[_totalsrc[y]]
                            }
                            // $('.tablepagewrap').html(res.result_page)
                            res.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            res.recordsTotal = _total;//返回数据全部记录
                            res.recordsFiltered = _total;//后台不实现过滤功能，每次查询均视作全部结果
                            res.data = _tempData;//后台不实现过滤功能，每次查询均视作全部结果
                            callback(res)


                        }        
                    },
                    complete:function(res){
                        // $('body').loading('close')
                    },
                    error:function(res){
                        
                    }    
                })
            }
        }
        var _dataTable = ''
        if(settings.service){
            _dataTable = $(domName).DataTable(_tbConfig);

            settings.init=function(){

                // _dataTable.page(parseInt($.session.get(settings.sessionPageKey) ? $.session.get(settings.sessionPageKey) - 1 : 0)).draw(false)
            }
        }else{
            _dataTable = $(domName).DataTable(_tbConfig)
            if (baseFn.notNull($.session.get(settings.sessionPageKey))){
                var page = $.session.get(settings.sessionPageKey);
                _dataTable.page(page - 1).draw(false);
            }
        }
        if(settings.select == true || settings.select == 'multi'){
            _dataTable.on('select.dt',function(){
                var selected = _dataTable.rows( { selected: true } ).count()
                var _rows =  _dataTable.rows().count()
                //$('.dtcount').text(selected)
                var _all = $(domName).find('.datatable-checkall')
                _rows == selected?_all.addClass('selected'):_all.removeClass('selected')
                settings.selecd(_dataTable.rows( { selected: true }))
            })
            _dataTable.on('deselect.dt',function(r){
                //console.log(_dataTable.rows($(r).parents('tr')).data())
                settings.deselecd(_dataTable.rows( { selected: true }))
                // var selected = _dataTable.rows( { selected: true } ).count()
                $(domName).find('.datatable-checkall').removeClass('selected')
                // $('.dtcount').text(selected)
                settings.deselecd(_dataTable.rows( { selected: true }))
                
            })
            $(domName).find('.datatable-checkall').click(function(){
                $(this).toggleClass('selected')
                if($(this).hasClass('selected')){
                    _dataTable.rows().select()
                }else{
                    _dataTable.rows().deselect()
                } 
            })
        }
        _dataTable.on('init.dt',function(e,sets,json){
            settings.init(_dataTable,e,sets,json)
        })
        _dataTable.on('page.dt',function(e,sets,json){
            if (baseFn.notNull(settings.sessionPageKey)){
                $.session.set(settings.sessionPageKey,_dataTable.page() + 1);
            }
            settings.page(_dataTable,e,sets,json)
        })
        return _dataTable
    },
    dateTimePick:function(domName,_objs){
        // $('#birthDay').datetimepicker({
        //     minView: "month", //选择日期后，不会再跳转去选择时分秒
        //     language:  'zh-CN',
        //     format: 'Y-m-d',
        //     todayBtn:  1,
        //     autoclose: 1,
        //     timepicker:false

        // });
        //时间选择函数
        //dateTimePicker
        var defaults={
            lang: 'zh',
            format: 'Y-m-d',
            formatDate: 'Y-m-d',
            dayOfWeekStart:1,
            timepicker:false,
            maxDate:true,
            onShow:function(){},
            onSelectDate:function(){},
            onSelectTime:function(){}
        }
        var settings = $.extend({}, defaults, _objs);
        if(settings.timepicker){
            settings.format='Y-m-d H:i'
            // settings.formatDate='Y-m-d H:i'
        }
        $(domName).datetimepicker(settings);
    },
    dateTimePickGroup:function(domName,objs){
        var _this = $(domName),_start = $(domName).find('.selstart'),_end = $(domName).find('.selend')
        var _seled={
            startseled:function(){},
            endseled:function(){}
        }
        if(objs.startseled){
            _seled.startseled = objs.startseled
        }
        if(objs.endseled){
            _seled.endseled = objs.endseled
        }
        var defaults={
            lang: 'zh',
            format: 'Y-m-d',
            formatDate: 'Y-m-d',
            dayOfWeekStart:1,
            timepicker:false,
            maxDate:true,
            onShow:function(){},
            onSelectDate:function(){},
            startseled:function(){},
            endseled:function(){},
            startsel:function(){
                var startDate = $.trim(_this.find('.selstart').val());
                var endDate = $.trim(_this.find('.selend').val());
                if (endDate != '' &&Date.parse(new Date(endDate)) < Date.parse(new Date(startDate))) {
                    baseFn.infoDialog('开始日期不能大于结束日期');
                    _this.find('.selstart').val('');
                    return false;
                }
                _seled.startseled()
            },
            endsel:function(){
                var startDate = $.trim(_this.find('.selstart').val());
                var endDate = $.trim(_this.find('.selend').val());
                if (startDate == '') {
                    baseFn.infoDialog('请先选择开始日期');
                    _this.find('.selend').val('');
                    return false;
                }
                if (Date.parse(new Date(endDate)) < Date.parse(new Date(startDate))) {
                    baseFn.infoDialog('结束日期不能小于开始日期');
                    _this.find('.selend').val('');
                    return false;
                }
                _seled.endseled()
            }
        }
        
        var _start=$.extend({},defaults,objs || {})
        var _end=$.extend({},defaults,objs || {})
        if(_start.timepicker){
            _start.format='Y-m-d H:i'
            // _start.formatDate='Y-m-d H:i'
        }
        if(_end.timepicker){
            _end.format='Y-m-d H:i'
            // _start.formatDate='Y-m-d H:i'
        }
        _start.onSelectDate=_start.startsel
        _end.onSelectDate=_end.endsel
        //开始时间筛选
        this.dateTimePick(domName + ' .selstart',_start)
        //结束时间筛选
        this.dateTimePick(domName + ' .selend',_end)
    },
    isFn:function(fn){
        return !!fn&&!fn.nodename&&fn.constructor!=String&&fn.constructor!=RegExp&&fn.constructor!=Array&&/function/i.test(fn+"")
    },
    imgUpload:function(domId,callback){
        var formDataPic = new FormData(document.getElementById(domId))
        $.ajax({
            url: baseUrl.base + "imgUploadCtl/uploadAliOSS",
            type:"POST",
            data:formDataPic,
            cache: false,
            contentType: false,  
            processData: false,
            dataType:"json",
            success:function(res){
                if(res.status == 'error'){
                }else if(res.status == 'success'){
                    callback({
                        width:res.width,
                        height:res.height,
                        url:res.url
                    })
                } 
            },
            complete:function(res){
            },
            error:function(res){
            }    
        })
    },
    getQueryString:function(name,isString){
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)return  decodeURI(r[2]); 
        if(isString){
            if(r==null) return '';
        }
        return null;
    },
    imgSize:function(opts){
        var _img = new Image();
        _img.src=opts.src;
        _img.onload=function(){
            if(_img.width/_img.height >opts.ratio){
                opts.hFn(opts.otherData)
            }else{
                opts.wFn(opts.otherData)
            }
        }
    },
    notNull:function(strings,kus){
        var _kus = ''
        if(arguments[1]){
            _kus = null 
        }
        if(strings != null && strings != undefined && strings !== _kus){
            return true
        }else{
            return false
        }
    },
    notNull2:function(strings,rd,kus){
        var _kus = ''
        if(arguments[2]){
            _kus = null 
        }
        if(strings != null && strings != undefined && strings !== _kus){
            if(arguments[1]){
                return strings
            }else{
                return true
            }
        }else{
            if(arguments[1] && arguments[2]){
                return arguments[2]
            }else{
                return false
            }
            
        }
    },
    deepcopy:function(obj){
        //多维数组深拷贝
        var out = [],i = 0,len = obj.length;
        for (; i < len; i++) {
            if (obj[i] instanceof Array){
                out[i] = deepcopy(obj[i]);
            }
            else out[i] = obj[i];
        }
        return out;
    },
    objDeepCopy:function (source) {
        //数组对象深拷贝
        var sourceCopy = source instanceof Array ? [] : {};
        for (var item in source) {
            sourceCopy[item] = typeof source[item] === 'object' ? this.objDeepCopy(source[item]) : source[item];
        }
        return sourceCopy;
    },
    objDelElm:function(obj,array){
        for(var i in obj){
            if(array){
                if(!(Object.prototype.toString.call(array)=='[object Array]')){
                    array=[array]
                }
                if(array.some(function(val){
                    return val == i
                })){
                   continue; 
                }
            }
            delete obj[i]
        }
    },
    isArray:function(o){
        return Object.prototype.toString.call(o)=='[object Array]';
    },
    $get:function(obj){
        var that = this
        var defaults={
            url:baseUrl.base,
            data:'',
            calCode:'code',
            calDataCode:0,
            calData:'results',
            calMsg:'msg',
            canNull:false,
            oCalFn:false,
            calFn:function(data){},
            comFn:function(){}
        }
        var settings=$.extend({},defaults,obj || {})
        settings.url = baseUrl.base+settings.url
        $.get(settings.url,settings.data,function(res){
            if(settings.calDataCode==res[settings.calCode]){
                if(that.notNull(res[settings.calData])){
                    settings.calFn(res[settings.calData])
                }else{
                    if(settings.canNull){
                        settings.calFn({})
                    }else{
                        that.infoDialog('数据为null')
                    }
                }
            }else{
                if(!settings.oCalFn){
                    that.infoDialog(res[settings.calMsg])
                }else{
                    settings.oCalFn(res)
                }
            }
        },'json').complete(function(){
            settings.comFn()
        })
    },
    $post:function(obj){
        var that = this
        var defaults={
            url:baseUrl.base,
            data:'',
            calCode:'code',
            calDataCode:0,
            calData:'results',
            calMsg:'msg',
            canNull:false,
            oCalFn:false,
            calFn:function(data){},
            comFn:function(){}
        }
        var settings=$.extend({},defaults,obj || {})
        settings.url = baseUrl.base+settings.url
        $.post(settings.url,settings.data,function(res){
            if(settings.calDataCode==res[settings.calCode]){
                if(that.notNull(res[settings.calData])){
                    settings.calFn(res[settings.calData])
                }else{
                    if(settings.canNull){
                        settings.calFn({})
                    }else{
                        that.infoDialog('数据为null')
                    }
                }
            }else{
                if(!settings.oCalFn){
                    that.infoDialog(res[settings.calMsg])
                }else{
                    settings.oCalFn(res)
                }
                
            }
        },'json').complete(function(){
            settings.comFn()
        })
    },
    setDTPage:function(dtName,page){
        /*
            商品设置列表 goodslist
            服务设置列表 servicelist
        */
       sessionStorage.setItem('page',dtName+'-'+page)
    },
    getDTPage:function(dtName){
        var _curDTName = sessionStorage.getItem('page').split('-')
        if(this.notNull(_curDTName[0]) && _curDTName[0] == dtName){
            return _curDTName[1]
        }else{
            return 1
        }

    },
    getJson:function(url,action='GET'){
        const promise = new Promise((resolve,reject)=>{
            const handler = function(){
                if(this.readyState !== 4){
                    return;
                }
                if(this.status === 200){
                    resolve(this.response)
                }else{
                    reject(new Error(this.statusText))
                }
            }
            const ajx = new XMLHttpRequest();
            ajx.open(action,url)
            ajx.onreadystatechange = handler;
            ajx.setRequestHeader("Accept",'application/json')
            ajx.send()
        })
    }

}
var floatObj = function() {

    /*
     * 判断obj是否为一个整数
     */
    function isInteger(obj) {
        return Math.floor(obj) === obj
    }

    /*
     * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
     * @param floatNum {number} 小数
     * @return {object}
     *   {times:100, num: 314}
     */
    function toInteger(floatNum) {
        var ret = {times: 1, num: 0}
        var isNegative = floatNum < 0
        if (isInteger(floatNum)) {
            ret.num = floatNum
            return ret
        }
        var strfi  = floatNum + ''
        var dotPos = strfi.indexOf('.')
        var len    = strfi.substr(dotPos+1).length
        var times  = Math.pow(10, len)
        var intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10)
        ret.times  = times
        if (isNegative) {
            intNum = -intNum
        }
        ret.num = intNum
        return ret
    }

    /*
     * 核心方法，实现加减乘除运算，确保不丢失精度
     * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
     *
     * @param a {number} 运算数1
     * @param b {number} 运算数2
     * @param digits {number} 精度，保留的小数点数，比如 2, 即保留为两位小数
     * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
     *
     */
    function operation(a, b, digits, op) {
        var o1 = toInteger(a)
        var o2 = toInteger(b)
        var n1 = o1.num
        var n2 = o2.num
        var t1 = o1.times
        var t2 = o2.times
        var max = t1 > t2 ? t1 : t2
        var result = null
        switch (op) {
            case 'add':
                if (t1 === t2) { // 两个小数位数相同
                    result = n1 + n2
                } else if (t1 > t2) { // o1 小数位 大于 o2
                    result = n1 + n2 * (t1 / t2)
                } else { // o1 小数位 小于 o2
                    result = n1 * (t2 / t1) + n2
                }
                return result / max
            case 'subtract':
                if (t1 === t2) {
                    result = n1 - n2
                } else if (t1 > t2) {
                    result = n1 - n2 * (t1 / t2)
                } else {
                    result = n1 * (t2 / t1) - n2
                }
                return result / max
            case 'multiply':
                result = (n1 * n2) / (t1 * t2)
                return result
            case 'divide':
                result = (n1 / n2) * (t2 / t1)
                return result
        }
    }

    // 加减乘除的四个接口
    function add(a, b, digits) {
        return operation(a, b, digits, 'add')
    }
    function subtract(a, b, digits) {
        return operation(a, b, digits, 'subtract')
    }
    function multiply(a, b, digits) {
        return operation(a, b, digits, 'multiply')
    }
    function divide(a, b, digits) {
        return operation(a, b, digits, 'divide')
    }

    // exports
    return {
        add: add,
        subtract: subtract,
        multiply: multiply,
        divide: divide
    }
}();